package com.example.app1;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SettingsFragment extends Fragment {
    private static final String TAG = "SettingsFragment";

    EditText preUrl;
    EditText itemId;
    View pauseButton;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        LogUtil.info(TAG, "onCreateView");
        View settingView = inflater.inflate(R.layout.fragment_settings, container, false);
        this.preUrl = settingView.findViewById(R.id.urlInput);
        this.itemId = settingView.findViewById(R.id.itemId);
        this.pauseButton = settingView.findViewById(R.id.pause);

        // 异步加载
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        Handler handler = new Handler(Looper.getMainLooper());

        // 提交任务到线程池
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                // 模拟耗时操作
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                final String result = "耗时任务完成";
                // 在主线程更新 UI
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Map<String, String> cacheConfig = getConfigFromFile();
                        String cachePreUrl = null;
                        String cacheItemId = null;
                        if (cacheConfig != null) {
                            cachePreUrl = cacheConfig.get("preUrl");
                            cacheItemId = cacheConfig.get("itemId");
                        }
                        if (cachePreUrl == null) {
                            cachePreUrl = "http://8.138.130.26/n/novel/getItemContent?itemId=";
                        }
                        preUrl.setText(cachePreUrl);
//        preUrl.setText("https://r13j527822.vicp.fun/n/novel/getItemContent?itemId=");
                        if (cacheItemId == null) {
                            cacheItemId = "1176117";
                        }
                        itemId.setText(cacheItemId);
                    }
                });
            }
        });

        return settingView;

    }

    public String getPreUrl() {
        return this.preUrl.getText().toString();
    }

    public void setItemId(String text) {
        this.itemId.setText(text);
        String currentPreUrl = preUrl.getText().toString();
        new Thread(() -> savePrams(text, currentPreUrl)).start();
    }

    public String getItemId() {
        return this.itemId.getText().toString();
    }

    private void savePrams(String itemId, String preUrl) {
        try {
            String config = "{\"itemId\": \"" + itemId + "\", \"preUrl\": \"" + preUrl + "\"}";
            String dir = this.requireActivity().getExternalCacheDir().getAbsolutePath();
            String filePath = dir + "/config.json";
            PrintWriter pw = new PrintWriter(filePath, "UTF-8");
            pw.print(config);
            pw.flush();
            pw.close();
        } catch (Exception e) {
            LogUtil.info(TAG, "缓存参数失败：" + e.getMessage(), e);
        }
    }

    /**
     * 修改软按钮显示隐藏
     * @param isShow 是否显示
     */
    public void changePauseButtonStatus(boolean isShow) {
        LogUtil.info(TAG, "changePauseButtonStatus：" + isShow);
        if (isShow) {
            this.pauseButton.setVisibility(View.VISIBLE);  // 显示
        } else {
            this.pauseButton.setVisibility(View.GONE);  // 隐藏
        }
    }

    private Map<String, String> getConfigFromFile() {
        try {
            String dir = this.requireActivity().getExternalCacheDir().getAbsolutePath();
            String filePath = dir + "/config.json";
            File file = new File(filePath);
            if (!file.exists()) {
                return null;
            }
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
            StringBuilder sb = new StringBuilder();
            String s;
            while ((s = br.readLine()) != null) {
                sb.append(s);
            }
            JSONObject config = new JSONObject(sb.toString());
            Iterator<String> keys = config.keys();
            Map<String, String> resultMap = new HashMap<>();
            while (keys.hasNext()) {
                String k = keys.next();
                resultMap.put(k, config.getString(k));
            }
            return resultMap;
        } catch (Exception e) {
            LogUtil.info(TAG, "读取参数失败：" + e.getMessage(), e);
        }
        return null;
    }
}